import cocos
from cocos.director import director
from cocos.layer import Layer
from cocos.text import Label
from cocos.sprite import Sprite
from cocos.actions import ScaleTo
import pyglet  # 🔹 添加 pyglet 以加载图片资源

class ButtonGridLayer(Layer):
    is_event_handler = True  # 让 Layer 监听鼠标事件

    def __init__(self):
        super().__init__()
        self.buttons = []  # 存储所有按钮
        self.hovered_button = None  # 当前鼠标悬停的按钮

        # **🔹预加载图片，使用 pyglet.resource.image()**
        self.button_images = [
            pyglet.resource.image("button_bg.png"),  # 默认按钮
            pyglet.resource.image("button_bg_clicked.png")  # 被点击的按钮
        ]

        self.create_button_grid()

    def create_button_grid(self):
        cols = 10        
        rows = 6        
        start_x = 40    
        start_y = 500   
        btn_width = 70  
        btn_height = 40 
        h_spacing = 5   
        v_spacing = 5   

        for i in range(60):
            row = i // cols
            col = i % cols
            
            x = start_x + col * (btn_width + h_spacing)
            y = start_y - row * (btn_height + v_spacing)
            
            # 创建按钮背景（Sprite）
            button_bg = Sprite(self.button_images[0])  
            button_bg.position = (x, y)
            button_bg.scale_x = btn_width / button_bg.width
            button_bg.scale_y = btn_height / button_bg.height
            button_bg.id = i  
            button_bg.current_image_index = 0  # 存储当前图片索引
            self.add(button_bg)

            # 创建按钮标签
            label = Label(
                str(i),
                font_size=16,
                anchor_x='center',
                anchor_y='center',
                color=(255, 255, 255, 255)  
            )
            label.position = (x, y)
            self.add(label)

            self.buttons.append(button_bg)  # **存储按钮到列表**

    def on_mouse_motion(self, x, y, dx, dy):
        """ 检测鼠标是否悬停在按钮上 """
        hovered = None  

        for button in self.buttons:
            bx, by = button.position
            bw, bh = button.width * button.scale_x, button.height * button.scale_y

            if (bx - bw / 2) <= x <= (bx + bw / 2) and (by - bh / 2) <= y <= (by + bh / 2):
                hovered = button
                break

        if hovered != self.hovered_button:
            if self.hovered_button:
                self.hovered_button.do(ScaleTo(1.0, duration=0.1))
            
            if hovered:
                hovered.do(ScaleTo(1.2, duration=0.1))
            
            self.hovered_button = hovered  

    def on_mouse_press(self, x, y, buttons, modifiers):
        """ 检测鼠标点击 """
        for button in self.buttons:
            bx, by = button.position
            bw, bh = button.width * button.scale_x, button.height * button.scale_y

            if (bx - bw / 2) <= x <= (bx + bw / 2) and (by - bh / 2) <= y <= (by + bh / 2):
                print(f"按钮 {button.id} 被点击")
                
                # **🔹修正错误：使用 pyglet 资源对象**
                button.current_image_index = 1 - button.current_image_index  
                button.image = self.button_images[button.current_image_index]  

                # **点击缩放动画**
                button.do(ScaleTo(1.1, duration=0.1) + ScaleTo(1.0, duration=0.1))
                break  

if __name__ == "__main__":
    director.init(
        width=800,
        height=600,
        caption="按钮网格示例",
        resizable=True
    )
    scene = cocos.scene.Scene(ButtonGridLayer())
    director.run(scene)
